package com.trip.util;

import com.trip.dao.tables.pojos.UserDomain;
import com.trip.exception.ServiceException;
import com.trip.vo.CaptchaVo;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author hc24
 * @version 2017/9/28
 */
public class AuthUtil {

    private static final Map<String,UserDomain> authCache=new HashMap<>();

    private static final Map<String,CaptchaVo> codeMap=new HashMap<>();

    public static String createAuth(UserDomain user){
        user.setAuthToken(UUID.randomUUID().toString());

        authCache.put(user.getAuthToken(),user);

        return user.getAuthToken();
    }

    public static Integer getUserId(String authToken){
        UserDomain user=authCache.get(authToken);
        if(user==null)
            throw new ServiceException("Auth failed");
        return user.getId();
    }

    public static boolean validAuth(String authToken){
        UserDomain user=authCache.get(authToken);
        if(user!=null){
            long s= Duration.between(LocalDateTime.now(),user.getLastedLogin()).getSeconds();

            if(authToken.equals(user.getAuthToken())&& s<2*24*60*60){
                return true;
            }
        }
        authCache.remove(authToken);
        return false;
    }

    public static void addCode(String email,String code){
        codeMap.put(email,new CaptchaVo(code));
    }

    public static boolean validCode(String email,String code){
        CaptchaVo captchaVo=codeMap.get(email);
        if(captchaVo!=null){
            long s= Duration.between(LocalDateTime.now(),captchaVo.getCreateTime()).getSeconds();

            if(code.equals(captchaVo.getCode())&& s<10*60){
                return true;
            }
        }

        codeMap.remove(email);
        return false;
    }

}
